package com.yiren.backstage.communication.services.impl;

import com.dbz.drivingTools.utils.SerialUtil;
import com.yiren.backstage.communication.services.AbstractPortService;
import com.yiren.backstage.currency.constant.HostDeviceModelConstant;

import java.io.File;
import java.io.IOException;

/**
 * Time:2021/12/23 14:57
 * Author:xiaozan
 * Description:设备通讯服务实现类 串口
 */
public class SerialPortServiceImpl extends AbstractPortService {

    //private SerialPort serial;

    private SerialUtil serial;
    private int aspIdx = 0;   //大班长工业电脑三个串口，连接的第几个

    public SerialPortServiceImpl() {
        super();
        serial = new SerialUtil();
    }

    @Override
    public boolean start() {
        String model = android.os.Build.MODEL;
        String deviceName = null;
        if (HostDeviceModelConstant.FYT6025.equals(model) || HostDeviceModelConstant.SL8541.equals(model)) {
            deviceName = "/dev/ttyS4";
        } else if (HostDeviceModelConstant.T3.equals(model) || HostDeviceModelConstant.AM83500.equals(model)) {
            deviceName = "/dev/ttyS2";
        } else if (HostDeviceModelConstant.SL8541E.equals(model)) {
            deviceName = "/dev/ttyS1";
        } else if (HostDeviceModelConstant.EVB3561SV.equals(model)) {
            deviceName = "/dev/ttyMT1";
        } else if (model.contains(HostDeviceModelConstant.B906) || model.contains(HostDeviceModelConstant.AD101J) || model.contains(HostDeviceModelConstant.LEN6737M)) {
            deviceName = "/dev/ttyMT2";
            /*aspIdx++;
            if (aspIdx % 3 == 0) {
                deviceName = "/dev/ttyMT1";
            } else if (aspIdx % 3 == 1) {
                deviceName = "/dev/ttyMT2";
            } else if (aspIdx % 3 == 2) {
                deviceName = "/dev/ttyMT3";
            }*/
        }

        File file = new File(deviceName);
        if (!file.exists()) {
            if (dataCallback != null) dataCallback.onStateChange(0, "找不到串口设备");
            return false;
        }
        if (!file.canRead() || !file.canWrite()) {
            if (dataCallback != null) dataCallback.onStateChange(0, "没有串口读写权限");
            return false;
        }

        if (serial.openDevice(deviceName, 115200)) {
            inputStream = serial.getInputStream();
            outputStream = serial.getOutputStream();
            if (dataCallback != null) dataCallback.onStateChange(0, "串口连接成功");
            return true;
        } else {
            if (dataCallback != null) dataCallback.onStateChange(0, "打开串口失败");
            return true;
        }
    }

    @Override
    public void stop() throws Exception {
        super.stop();
        serial.closeDevice();
    }

    @Override
    public String read(byte[] data, int offset, int size) throws IOException {
        return super.read(data, offset, size);
    }

    @Override
    public void write(byte[] data) throws IOException {
        super.write(data);
    }
}
